<?php
/**
 * Member.php
 *
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2015-2025 山西牛酷信息科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: http://www.niushop.com.cn
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * @author : niuteam
 * @date : 2015.1.17
 * @version : v1.0.0.0
 */
namespace data\service;

/**
 * 薪水奖金服务层
*/

use addons\Nsfx\data\model\NfxCommissionDistributionModel;
use data\model\NsMemberLevelModel;
use data\model\NsMemberMinLevelModel;
use data\model\NsMemberModel;
use data\model\NsOrderModel;
use data\model\NsRegainAgentModel;
use data\service\Member as MemberService;
use data\model\NsSalaryModel;
use data\service\Mine\Mine;
use think\Db;

class Salary extends BaseService
{

    function __construct()
    {
        parent::__construct();
        $this->tax_rate = 0;
        $this->point_rate = 0;
        $this->remark = '';
        $this->member_name = '';
    }

    public function getSalaryName($category){
        switch($category)
        {
            case 1:
                $salaryType = "直接分享";
                break;
            case 2:
                $salaryType = "间接分享";
                break;
            case 3:
                $salaryType = "级差奖励";
                break;
            case 4:
                $salaryType = "平级奖励";
                break;
            case 5:
                $salaryType = "服务奖励";
                break;
            case 6:
                $salaryType = "区域代理奖励";
                break;
            case 7:
                $salaryType = "全网分红";
                break;
            case 8:
                $salaryType = "直接分享收益";
                break;
            case 9:
                $salaryType = "间接分享收益";
                break;
            case 10:
                $salaryType = "拓店收益";
                break;
            case 11:
                $salaryType = "上级收益";
                break;
            case 12:
                $salaryType = "上上级收益";
                break;
            default:
                $salaryType = "其他收益";
        }
        return $salaryType;
    }


    // 保存奖金
    public function addSalaryItem($uid,$category,$total_money,$balance,$points,$tax){
        //保存奖金日志
        $salary = new NsSalaryModel();
        $data = array(
            'uid' => $uid,
            'tax' => $tax,
            'point' => $points,
            'balance' => $balance,
            'total_money' => $total_money,
            'category' => $category,
            'add_time' => time(),
            'remark' => $this->remark
        );
        $retval = $salary->save($data);
    }

    // 实际发送奖金
    public function sendSalaryToAccount($uid,$category,$total_money,$balance,$points,$tax){
        $salary_name = $this->getSalaryName($category);
        $member = new MemberService();
        $retval = $member->addMemberAccount(0, 1, $uid, $balance, $this->member_name.$salary_name);
        //$retval = $member->addMemberAccount(0, 1, $uid, $points, $salary_name);
    }

    //发送奖金
    public function sendMemberSalary($uid,$money,$category,$member_name = ''){
        //trace('send_member_salary'.','.$uid.','.$money,'debug');
        // 如果uid为零，则直接返回
        if($uid == 0 or $money <=0){return 1;}

        $total_money = $money;
        $tax = $money * $this->tax_rate;
        $points = $money * $this->point_rate;
        $balance = $total_money - $tax - $points;
        $this->member_name = $member_name;

        // 检测对方还有多少共享银币，然后进行加速释放

        $memberAccount = new MemberService\MemberAccount();
        $salary = $memberAccount->getMemberSalary($uid);

        if($salary < $money){$money = $salary;}

        if($money <=0 ){return 1;}

        $money = round($money,2);
        $total_money = round($total_money,2);
        $total_money = $money;


        $retval = $memberAccount->addMemberAccountData(0, 4, $uid, 1, 0-$money, 1, 0, $member_name.'加速释放');

        if($retval > 0){
            //保存奖金记录
            $this->addSalaryItem($uid,$category,$total_money,$balance,$points,$tax);

            //发送奖金
            $this->sendSalaryToAccount($uid,$category,$total_money,$balance,$points,$tax);
        }

        return 1;
    }



    //  级差奖金
    public function releaseGradeSalary($uid,$give_rank_point){

        // 级差奖金
        $member = new Member();
        $info = $member->getMemberInfo(['uid'=>$uid],"parent_id,member_level,member_name");
        if($info){
            $true_level = $info['member_level'];
            $member_name = $info['member_name'];
            $member_level_model = new NsMemberLevelModel();
            $max_level_id = $member_level_model->getFirstData([],"level_id desc")['level_id'];
            $eqal_grade_uid = 0;
            $salary_money = 0;
            while ($info and $true_level <= $max_level_id){
                $parent_id = $info['parent_id'];
                if($parent_id == 0){break;}
                $send_grade_rate = 0;
                $level_info = $member->getLevelinfoByUid($parent_id);
                $member_level = $level_info['level_id'];
                // 高级
                if($member_level > $true_level){
                    $send_grade_rate = $member_level_model->get($member_level)['grade_rate'] - $member_level_model->get($true_level)['grade_rate'];

                    // 硬波比平级
                    //if($eqal_grade_uid) {$send_grade_rate = $send_grade_rate - 1;}

                    $true_level = $member_level;
                    $eqal_grade_uid = 0;
                }elseif($member_level == $true_level) {
                    //存在平级
                    if(!$eqal_grade_uid){
                        $eqal_grade_uid = $parent_id;
                        //$salary_money = 10 * $give_rank_point * 0.01;
                        $level_info = $member->getLevelinfoByUid($eqal_grade_uid);
                        $send_equal_rate = $level_info['equal_rate'];
                        $salary_money = $send_equal_rate * $salary_money * 0.01;
                        $this->sendMemberSalary($eqal_grade_uid,$salary_money,4,$member_name);
                    }
                }else{

                }

                if($send_grade_rate > 0){
                    $salary_money = $send_grade_rate * $give_rank_point * 0.01;
                    $this->sendMemberSalary($parent_id,$salary_money,3,$member_name);
                }
                $info = $member->getMemberInfo(['uid'=>$parent_id],"parent_id");

                if($max_level_id == $true_level){
                    $max_level_id = $max_level_id + 1;
                }
            }
        }
    }

    // 下级奖金
    public function releaseDownSalary($uid,$give_rank_point){

        $member_model = new NsMemberModel();
        $condition = ['parent_id'=>$uid,'member_level'=>['>',1]];
        $member_list = $member_model->all($condition);
        $down_count = count($member_list);
        trace('下级数量:'.$down_count,"debug");
        if($down_count == 0){
            return 1;
        }
        $give_rank_point = $give_rank_point / $down_count;
        $member = new Member();
        foreach ($member_list as $k => $v) {

            trace('下级奖金',"debug");
            trace($v['uid'],"debug");
            $uid = $v['uid'];
            $member_name = $v['member_name'];
            $level_info = $member->getLevelinfoByUid($uid);
            $salary_money = $level_info['down_rate'] * $give_rank_point * 0.01;
            $salary_money = round($salary_money,2);
            $this->sendMemberSalary($uid,$salary_money,11,$member_name);
        }
    }


    // 下级奖金
    public function releaseDown2Salary($uid,$give_rank_point){

        $member_model = new NsMemberModel();
        $condition = ['parent2_id'=>$uid,'member_level'=>['>',1]];
        $member_list = $member_model->all($condition);
        $down_count = count($member_list);
        trace('下级数量:'.$down_count,"debug");
        if($down_count == 0){
            return 1;
        }
        $give_rank_point = $give_rank_point / $down_count;
        $member = new Member();
        foreach ($member_list as $k => $v) {

            trace('下级奖金',"debug");
            trace($v['uid'],"debug");
            $uid = $v['uid'];
            $member_name = $v['member_name'];
            $level_info = $member->getLevelinfoByUid($uid);
            $salary_money = $level_info['down2_rate'] * $give_rank_point * 0.01;
            $this->sendMemberSalary($uid,$salary_money,12,$member_name);
        }
    }

    // 推荐奖金
    public function releaseReferSalary($uid,$give_rank_point){
        $member = new Member();
        $info = $member->getMemberInfo(['uid'=>$uid],"parent_id,member_name");

        // 分销奖金
        if($info){
            $parent_id = $info['parent_id'];
            $member_name = $info['member_name'];
            //获取等级信息
            $level_info = $member->getLevelinfoByUid($parent_id);
            $salary_money = $level_info['first_rate'] * $give_rank_point * 0.01;
            $this->sendMemberSalary($parent_id,$salary_money,1,$member_name);
            $info = $member->getMemberInfo(['uid'=>$parent_id],"parent_id");
            // 二级分销
            if($info){
                $parent_id = $info['parent_id'];
                $level_info = $member->getLevelinfoByUid($parent_id);

                $salary_money = $level_info['second_rate'] * $give_rank_point * 0.01;
                $this->sendMemberSalary($parent_id,$salary_money,2,$member_name);
            }
        }
    }



    // 推荐奖金
    public function orderReferSalary($order_id){
        $order = new NsOrderModel();
        $order_info = $order->get($order_id);
        $this->order_no = $order_info['order_no'];
        $uid = $order_info['buyer_id'];
        $give_rank_point = $order_info['give_rank_point'];

        $member = new Member();
        $info = $member->getMemberInfo(['uid'=>$uid],"parent_id");

        // 分销奖金
        if($info){
            $parent_id = $info['parent_id'];
            //获取等级信息
            $level_info = $member->getLevelinfoByUid($parent_id);
            $salary_money = $level_info['first_rate'] * $give_rank_point * 0.01;
            $this->sendMemberSalary($parent_id,$salary_money,1);
            $info = $member->getMemberInfo(['uid'=>$parent_id],"parent_id");
            // 二级分销
            if($info){
                $parent_id = $info['parent_id'];
                $level_info = $member->getLevelinfoByUid($parent_id);

                $salary_money = $level_info['second_rate'] * $give_rank_point * 0.01;
                $this->sendMemberSalary($parent_id,$salary_money,2);
            }
        }
    }

    // 董事分红
    public function orderGlobleSalary($order_id){
        $order = new NsOrderModel();
        $order_info = $order->get($order_id);
        $give_rank_point = $order_info['give_rank_point'];
        $globle_rate = 5;
        $member = new Member();
        $condition = ['nm.member_level'=>9];
        $list = $member->getMemberList(1,0,$condition);
        $total_count = $list['total_count'];
        //trace("全局分红","debug");
        if($total_count)
        {
            foreach ($list['data'] as $k => $v) {
                $salary_money = $globle_rate * $give_rank_point * 0.01/$total_count;
                $this->sendMemberSalary($v['uid'],$salary_money,7);
            }
        }

    }


    //  店铺级差服务费
    public function orderShopGradeSalary($order_id){
        $order = new NsOrderModel();
        $order_info = $order->get($order_id);
        $uid = $order_info['buyer_id'];
        $give_rank_point = $order_info['give_rank_point'];


        //$mine = new Mine();
        //$res = $mine->getCurPrice();
       // trace('今日金价'.$res,"debug");
        if(1) {
            //$give_rank_point = $give_rank_point / $res;
            //trace('店铺级差服务费',"debug");
            // 店铺级差服务费
            $member = new Member();
            $info = $member->getMemberInfo(['uid' => $uid], "parent_id");
            $eqal_grade_uid = 0;
            $salary_money = 0;
            if ($info) {
                $true_min_level = 1;
                $member_min_level_model = new NsMemberMinLevelModel();
                $max_min_level_id = $member_min_level_model->getFirstData([], "min_level_id desc")['min_level_id'];

                while ($info and $true_min_level < $max_min_level_id) {
                    $parent_id = $info['parent_id'];
                    if ($parent_id == 0) {
                        break;
                    }
                    $send_service_grade_rate = 0;
                    $min_level_info = $member->getMinLevelinfoByUid($parent_id);
                    $member_min_level = $min_level_info['min_level_id'];
                    //
                    trace('高级',"debug");
                    trace($member_min_level,"debug");
                    trace($true_min_level,"debug");


                    if ($member_min_level > $true_min_level) {
                        $send_service_grade_rate = $member_min_level_model->get($member_min_level)['min_service_rate'] - $member_min_level_model->get($true_min_level)['min_service_rate'];
                        $true_min_level = $member_min_level;
                        $eqal_grade_uid = 0;
                    }elseif($member_min_level == $true_min_level) {
                        //存在平级

                        /*
                        trace('存在平级',"debug");
                        if(!$eqal_grade_uid){
                            $eqal_grade_uid = $parent_id;
                            //$salary_money = 10 * $give_rank_point * 0.01;
                            $salary_money = $salary_money * 0.05;
                            $memberAccount = new MemberService\MemberAccount();
                            $retval = $memberAccount->addMemberAccountData(0, 3, $parent_id, 1, $salary_money, 1, 0, '平级市场收益');

                        }
                        */
                    }else{

                    }

                    if ($send_service_grade_rate > 0) {
                        $salary_money = $send_service_grade_rate * $give_rank_point;
                        //$this->sendMemberSalary($parent_id, $salary_money, 5);

                        $memberAccount = new MemberService\MemberAccount();
                        $retval = $memberAccount->addMemberAccountData(0, 3, $parent_id, 1, $salary_money, 1, 0, '市场收益');


                        if($true_min_level == $max_min_level_id){
                            //计算最后一个平级
                            $info = $member->getMemberInfo(['uid' => $parent_id], "parent_id");
                            if($info){
                                $min_level_info = $member->getMinLevelinfoByUid($info['parent_id']);
                                $member_min_level = $min_level_info['min_level_id'];
                                if($member_min_level == $max_min_level_id){
                                    $salary_money = $salary_money * 0.05;
                                    $memberAccount = new MemberService\MemberAccount();
                                    $retval = $memberAccount->addMemberAccountData(0, 3, $info['parent_id'], 1, $salary_money, 1, 0, '平级市场收益');

                                }
                            }
                        }


                    }
                    $info = $member->getMemberInfo(['uid' => $parent_id], "parent_id");
                }
            }
        }

    }


    //  区域代理服务费
    public function orderRegainAgentSalary($order_id){
        //trace('区域代理服务费',"debug");
        $order = new NsOrderModel();
        $order_info = $order->get($order_id);
        $give_rank_point = $order_info['give_rank_point'];
        $receiver_city = $order_info['receiver_city'];
        $regain_agent_model = new NsRegainAgentModel();
        trace($receiver_city,"debug");
        $info = $regain_agent_model->getInfo(['agent_city_id'=>$receiver_city,'agent_type'=>2],"uid");
        trace('区域代理服务费',"debug");
        trace($info,"debug");
        if($info)
        {

            $mine = new Mine();
            $res = $mine->getCurPrice();
            trace('今日金价'.$res,"debug");
            if($res) {
                $give_rank_point = $give_rank_point / $res;
                $uid = $info['uid'];
                $salary_money =  $give_rank_point;
                $memberAccount = new MemberService\MemberAccount();
                $retval = $memberAccount->addMemberAccountData(0, 2, $uid, 1, $salary_money, 1, 0, '城市代理');
            }

        }
    }

    //  级差奖金
    public function orderGradeSalary($order_id){
        $order = new NsOrderModel();
        $order_info = $order->get($order_id);
        $uid = $order_info['buyer_id'];
        $give_rank_point = $order_info['point'];

        // 级差奖金
        $member = new Member();
        $info = $member->getMemberInfo(['uid'=>$uid],"parent_id");
        if($info){
            $true_level = 2;
            $member_level_model = new NsMemberLevelModel();
            $max_level_id = $member_level_model->getFirstData([],"level_id desc")['level_id'];
            $eqal_grade_uid = 0;
            while ($info and $true_level < $max_level_id){
                $parent_id = $info['parent_id'];
                if($parent_id == 0){break;}
                $send_grade_rate = 0;
                $level_info = $member->getLevelinfoByUid($parent_id);
                $member_level = $level_info['level_id'];
                // 高级
                if($member_level > $true_level){

                    //$send_grade_rate = ($member_level - $true_level)*5;
                    $send_grade_rate = $member_level_model->get($member_level)['point_grade_rate'] - $member_level_model->get($true_level)['point_grade_rate'];


                    $true_level = $member_level;
                    //$eqal_grade_uid = 0;
                }

                if($send_grade_rate > 0){
                    $salary_money = $send_grade_rate * $give_rank_point * 0.01;
                    $memberAccount = new MemberService\MemberAccount();
                    $retval = $memberAccount->addMemberAccountData(0, 1, $parent_id, 1, $salary_money, 1, 0, '珠宝专区');

                }
                $info = $member->getMemberInfo(['uid'=>$parent_id],"parent_id");
            }
        }
    }


    // 推荐奖金
    public function orderVipReferSalary($order_id){
        $order = new NsOrderModel();
        $order_info = $order->get($order_id);
        $this->order_no = $order_info['order_no'];
        $uid = $order_info['buyer_id'];
        $give_rank_point = $order_info['give_rank_point'];
        $member = new Member();
        $info = $member->getMemberInfo(['uid'=>$uid],"parent_id");

        // 分销奖金
        if($info){
            $parent_id = $info['parent_id'];
            //获取等级信息
            $first_rate = 10;
            $salary_money = $first_rate * $give_rank_point * 0.01;
            $this->sendMemberSalary($parent_id,$salary_money,1);
            $info = $member->getMemberInfo(['uid'=>$parent_id],"parent_id");
            // 二级分销
            if($info){
                $parent_id = $info['parent_id'];
                $second_rate = 10;
                $salary_money = $second_rate * $give_rank_point * 0.01;
                $this->sendMemberSalary($parent_id,$salary_money,2);
            }
        }
    }

    /**
     * 全网分红
     * 20220320版，由计划任务调用执行
     * 订单购买时按比例进入分红池，每周日晚分红
     */
    public function globleLeaderSalary(){
        $week_order_total = Db::name('sys_config')->where(['instance_id' => 0, 'key' => 'LEADER_POOL'])->value('value');
        if ($week_order_total > 0) {
            Db::startTrans();
            try {
                $need_levels = Db::name('ns_member_level')->where('leader_rate>0')->select();
                foreach ($need_levels as $item) {
                    $all_reward = $week_order_total * $item['leader_rate'] * 0.01;
                    $all_member = Db::name('ns_member')->where(['member_level' => $item['level']])->select();
                    if ($all_reward > 0 && count($all_member) > 0) {
                        $reward = round($all_reward / count($all_member), 2);
                        if ($reward > 0) {
                            foreach ($all_member as $member) {
                                $this->sendMemberSalary($member['uid'], $reward,7, $member['member_name']);dump(555);exit;
                                $commossion_distribution = new NfxCommissionDistributionModel();
                                $data = array(
                                    'serial_no' => getSerialNo(),
                                    'shop_id' => 0,
                                    'income_uid' => $member['uid'],
                                    'promoter_id' => 0,
                                    'promoter_level' => 0,
                                    'order_id' => 0,
                                    'order_goods_id' => 1,
                                    'goods_money' => 0,
                                    'goods_cost' => 0,
                                    'goods_return' => 0,//折扣
                                    'goods_commission_rate' => 0,
                                    'commission_rate' => 0,
                                    'commission_money' => $reward,
                                    'create_time' => time(),
                                    'is_issue' => 1,
                                    'reward_type' => 5,//分享佣金,public $reward_type = [1 => '分享佣金', 2 => '培育奖励', 3 => '团队奖励', 4 => '极差奖', 5 => '全网分红'];
                                );

                                $commossion_distribution->save($data);
                            }
                        }
                    }
                }

                //清空分红池
                Db::name('sys_config')->where(['instance_id' => 0, 'key' => 'LEADER_POOL'])->update(['value' => 0]);

                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                echo $exception->getMessage();
            }
        }
    }
}
